import BaseAsset from "../base/BaseAsset";

declare let cc: typeof window.cc;

/**
 * cocos creator资源加载管理
 * @author cls
 * @date 2020-01-20
 */
export default class CCCAsset extends BaseAsset {
    /** 加载预制件 */
    async loadPrefab(path: string){
        return this.loadAssetsAsync(path, cc.Prefab);
    }

    /** 加载帧图片 */
    async loadImage(path: string): Promise<cc.SpriteFrame> {
        return this.loadAssetsAsync(path, cc.SpriteFrame);
    }

    /** 加载图集 */
    async loadSpriteAtlas(path: string): Promise<cc.SpriteAtlas> {
        return this.loadAssetsAsync(path, cc.SpriteAtlas);
    }

    /** 加载音频 */
    async loadAudioClip(path: string): Promise<cc.AudioClip> {
        return this.loadAssetsAsync(path, cc.AudioClip);
    }

    /** 加载配置 */
    async loadConfig(path: string): Promise<cc.JsonAsset> {
        return this.loadAssetsAsync(path, cc.JsonAsset);
    }

    /** 加载动画Clip */
    async loadAnimClip(path: string): Promise<cc.AnimationClip> {
        return this.loadAssetsAsync(path, cc.AnimationClip);
    }

    async loadAssetsAsync(path: string, type: typeof cc.Asset): Promise<any> {
        return new Promise((resolve: Function, reject: Function) => {
            let _self = this;
            if (_self._assetsList[path]) {
                resolve(_self._assetsList[path]);
            } else {
                cc.loader.loadRes(path, type, function (err, res) {
                    if (err) {
                        reject();
                        console.error(`***** 找不到资源 path: ${path} *****`);
                        return;
                    }
                    _self._assetsList[path] = res;
                    resolve(res);
                });
            }
        });
    }

    releaseRes(resPath: string) {
        cc.loader.releaseRes(resPath);
        this._assetsList[resPath] = null;
    }
}
